package com.base.event
{
	import com.base.Main;
	import com.base.data.DataCenter;
	import com.base.data.account.AccountBean;
	import com.base.data.message.MessageBean;
	import com.base.data.sendrule.SendRuleBean;
	import com.base.send.SendMessage;
	import com.base.ui.other.StatusWindow;
	import com.city58.City58Send;
	
	import flash.desktop.NativeApplication;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.setTimeout;

	public class EventsManager extends EventDispatcher
	{
		
		private static var _instance : EventsManager;
		
		public static function get instance() : EventsManager {
			if ( !_instance ) {
				_instance = new EventsManager();
			}
			return _instance;
		}
		
		public function EventsManager()
		{
			if( _instance ) throw new Error("请使用单例访问");
		}
		
		public function init( fun:Function ):void {
			NativeApplication.nativeApplication.addEventListener( Event.EXITING , onExiting );
			NativeApplication.nativeApplication.addEventListener( CustomEvent.Send_Time , onSendTimer );
			
			if( fun != null ) fun();
		}
		
		protected function onExiting( e:Event ):void {
			DataCenter.instance.save();
		}
		
		private var msgList:Array;
		
		private var actList:Array;
		
		protected function onSendTimer( e:CustomEvent ):void {
			Main.showStatusBtn();
			
			var sendRule:SendRuleBean = e.data as SendRuleBean;
			msgList = new Array();
			actList = new Array();
			
			for each( var msgItem:MessageBean in DataCenter.instance.msgList ) {
				if( msgItem.sendRuleId == sendRule.ruleId ) msgList.push( msgItem );
			}
			
			for each( var actItem:AccountBean in DataCenter.instance.accountList ) {
				if( actItem.type == sendRule.type ) actList.push( actItem );
			}
			
			startSend( msgList,actList );
		}
		
		private function startSend( msgList:Array , actList:Array ):void {
			if( msgList.length > 0 ) {
				var send:SendMessage = new City58Send();
				var acts:Array = actList.concat();	
				send.send( acts,msgList.shift() ,sendSuccessCallBack , sendFailureCallBack );
			}
		}
		
		private function sendSuccessCallBack( param:* ):void {
			StatusWindow.addText(City58Send(param).messageBean.titleStr+"的帖子发送成功");
			setTimeout( startSend,1000*5 , msgList , actList );
		}
		
		private function sendFailureCallBack( param:* ):void {
			var msg:String = City58Send(param).context.replace(/[^\u4E00-\u9FA5]/g,"");
			StatusWindow.addText("发帖失败 原因为:"+ msg );
			startSend( msgList , actList );
		}
		
		
	}
}